package org.example.service;


import jakarta.annotation.Resource;
import org.example.entity.LoginDTO;
import org.example.entity.MyUserDetails;
import org.example.entity.ResponseModel;
import org.example.util.JwtUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class LoginService {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private AuthenticationManager authenticationManager;

    public ResponseModel<String> checkLogin(LoginDTO dto) {
        // 获取用户名密码
        String username = dto.getUsername();
        String password = dto.getPassword();
        // 尝试创建一个待认证的对象
        UsernamePasswordAuthenticationToken authRequest =
                new UsernamePasswordAuthenticationToken(username, password);
        // 发起认证
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(authRequest);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // 判断是否真正成功
        if (authentication != null && authentication.isAuthenticated()) {
            // 认证成功后放入安全上下文中供后续过滤器使用（重要）
            SecurityContextHolder.getContext().setAuthentication(authentication);
            // 生成token
            String subject = "user:"+((MyUserDetails) authentication.getPrincipal()).getMyUser().getId();

            String token = JwtUtil.createToken(subject, JwtUtil.EXPIRE_TIME);

            redisTemplate.opsForValue().set(subject, authentication.getPrincipal(), JwtUtil.EXPIRE_TIME, TimeUnit.MILLISECONDS);

            return ResponseModel.authSuccess(token);
        } else {
            return ResponseModel.authFailure("认证失败");
        }
    }


}
